﻿using HalconDotNet;
using LeaderCCSLaserUI.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using ViewROI;
using static System.Windows.Forms.MonthCalendar;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs.VisionProgram
{
    public class FunctionBlobCircleDialogViewModel : DialogViewModel
    {
        #region 变量
        private HObject mImage;
        private readonly DrawROI drawROI;
        private bool isClosing = false;
        #endregion
        #region 属性
        private HImage cameraImage0;
        public HImage CameraImage0
        {
            get { return cameraImage0; }
            set { SetProperty(ref cameraImage0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }

        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private BlobCircleParamDisp mBlobCircleParamDisp;
        public BlobCircleParamDisp MBlobCircleParamDisp
        {
            get { return mBlobCircleParamDisp; }
            set { SetProperty(ref mBlobCircleParamDisp, value); }
        }
        private bool isDrawing;
        public bool IsDrawing
        {
            get { return isDrawing; }
            set { SetProperty(ref isDrawing, value); }
        }
        #endregion
        #region 函数
        private DelegateCommand openImageCommand;
        public DelegateCommand OpenImageCommand =>
            openImageCommand ?? (openImageCommand = new DelegateCommand(ExecuteOpenImageCommand));
        private DelegateCommand<object> operateCommandCommand;
        public DelegateCommand<object> OperateCommandCommand =>
            operateCommandCommand ?? (operateCommandCommand = new DelegateCommand<object>(ExecuteOperateCommandCommand));
        private DelegateCommand retateImageCommand;
        public DelegateCommand RetateImageCommand =>
            retateImageCommand ?? (retateImageCommand = new DelegateCommand(ExecuteRetateImageCommand));
        private DelegateCommand actionCommand;
        public DelegateCommand ActionCommand =>
            actionCommand ?? (actionCommand = new DelegateCommand(ExecuteActionCommand));
        private DelegateCommand drawCircleCommand;
        public DelegateCommand DrawCircleCommand =>
            drawCircleCommand ?? (drawCircleCommand = new DelegateCommand(ExecuteDrawCircleCommand));

        void ExecuteDrawCircleCommand()
        {
            if (CameraImage0 != null)
            {
                try
                {
                    CameraAppendHObject0 = null;
                    CameraAppendHMessage0 = null;
                    IsDrawing = true;
                    var roi = drawROI.imageViewer.DrawROI(ROI.ROI_TYPE_CIRCLE);
                    IsDrawing = false;
                    if (!isClosing)
                    {
                        var circle = roi.getRegion();
                        CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        CameraAppendHObject0 = circle;
                        HOperatorSet.RegionFeatures(circle, "row", out var row);
                        HOperatorSet.RegionFeatures(circle, "column", out var column);
                        HOperatorSet.RegionFeatures(circle, "ra", out var radius);
                        MBlobCircleParamDisp.Row = Math.Round(row.D, 0);
                        MBlobCircleParamDisp.Column = Math.Round(column.D, 0);
                        MBlobCircleParamDisp.Radius = Math.Round(radius.D, 1);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteActionCommand()
        {
            if (CameraImage0 != null)
            {
                try
                {
                    CameraAppendHObject0 = null;
                    CameraAppendHMessage0 = null;

                    var MBlobCircleParam = new BlobCircleParam
                    {
                        Row = MBlobCircleParamDisp.Row,
                        Column = MBlobCircleParamDisp.Column,
                        Radius = MBlobCircleParamDisp.Radius,
                        MinGray = MBlobCircleParamDisp.MinGray,
                        MaxGray = MBlobCircleParamDisp.MaxGray,
                        OpeningRadius = MBlobCircleParamDisp.OpeningRadius,
                        SelectAreaMin = MBlobCircleParamDisp.SelectAreaMin,
                        SelectAreaMax = MBlobCircleParamDisp.SelectAreaMax,
                        SelectRadiusMin = MBlobCircleParamDisp.SelectRadiusMin,
                        SelectRadiusMax = MBlobCircleParamDisp.SelectRadiusMax,
                    };
                    HTuple row = new HTuple(MBlobCircleParam.Row), column = new HTuple(MBlobCircleParam.Column), angle = new HTuple(0), score = new HTuple(0), v1 = new HTuple(0), v2 = new HTuple(0); HObject region, maxRegion;
                    HOperatorSet.GenEmptyObj(out region);
                    HOperatorSet.GenEmptyObj(out maxRegion);
                    var r = MFunc.FunDictionary["BlobCircle"].Run(ref mImage, JsonConvert.SerializeObject(MBlobCircleParam, Formatting.Indented), ref row, ref column, ref angle, ref score, ref maxRegion, ref region, ref v1, ref v2);
                    if (r)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraAppendHObject0 = region;
                        HOperatorSet.RegionFeatures(region, "area", out var hv_area);
                        HOperatorSet.RegionFeatures(region, "ra", out var hv_ra);
                        CameraAppendHMessage0 = new HMsgEntry($"面积:{hv_area.D:f0}\n半径:{hv_ra.D:f0}", 10, 10, "magenta", "window", "box", "false", 24, "mono", "true", "false");
                    }
                    else
                    {
                        CameraGCStyle0 = new Tuple<string, object>("Color", "medium blue");
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraAppendHObject0 = maxRegion;
                        HOperatorSet.RegionFeatures(maxRegion, "area", out var hv_area);
                        HOperatorSet.RegionFeatures(maxRegion, "ra", out var hv_ra);
                        CameraAppendHMessage0 = new HMsgEntry($"NG\n面积:{hv_area.D:f0}\n半径:{hv_ra.D:f0}", 40, 40, "orange red", "window", "box", "false", 24, "mono", "true", "false");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteRetateImageCommand()
        {
            if (CameraImage0 != null)
            {
                HOperatorSet.RotateImage(CameraImage0, out mImage, 90, "constant");
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteOperateCommandCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "确认":
                    {
                        try
                        {
                            var MBlobCircleParam = new BlobCircleParam
                            {
                                Row = MBlobCircleParamDisp.Row,
                                Column = MBlobCircleParamDisp.Column,
                                Radius = MBlobCircleParamDisp.Radius,
                                MinGray = MBlobCircleParamDisp.MinGray,
                                MaxGray = MBlobCircleParamDisp.MaxGray,
                                OpeningRadius = MBlobCircleParamDisp.OpeningRadius,
                                SelectAreaMin = MBlobCircleParamDisp.SelectAreaMin,
                                SelectAreaMax = MBlobCircleParamDisp.SelectAreaMax,
                                SelectRadiusMin = MBlobCircleParamDisp.SelectRadiusMin,
                                SelectRadiusMax = MBlobCircleParamDisp.SelectRadiusMax,
                            };
                            string jsonString = JsonConvert.SerializeObject(MBlobCircleParam, Formatting.Indented);
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", jsonString);
                            OnRequestClose(new Prism.Services.Dialogs.DialogResult(ButtonResult.Yes, param));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    break;
                case "取消":
                    OnRequestClose(new Prism.Services.Dialogs.DialogResult(ButtonResult.Cancel));
                    break;
                default:
                    break;
            }
        }
        void ExecuteOpenImageCommand()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (mImage != null)
                {
                    mImage.Dispose();
                }
                HOperatorSet.ReadImage(out mImage, openFileDialog.FileName);
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
        }
        #endregion
        #region 导航
        public override void OnDialogClosed()
        {
            isClosing = true;
            if (IsDrawing)
            {
                MFunc.HIOCancelDraw();
            }
        }
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            try
            {
                var jsonString = parameters.GetValue<string>("Parameter");
                var _image = parameters.GetValue<HObject>("Image");
                if (_image != null)
                {
                    mImage = _image.CopyObj(1, -1);
                    CameraImage0 = new HImage(mImage.CopyObj(1, -1));
                }
                var MBlobCircleParam = JsonConvert.DeserializeObject<BlobCircleParam>(jsonString);
                MBlobCircleParamDisp = new BlobCircleParamDisp
                {
                    Row = MBlobCircleParam.Row,
                    Column = MBlobCircleParam.Column,
                    Radius = MBlobCircleParam.Radius,
                    MinGray = MBlobCircleParam.MinGray,
                    MaxGray = MBlobCircleParam.MaxGray,
                    OpeningRadius = MBlobCircleParam.OpeningRadius,
                    SelectAreaMin = MBlobCircleParam.SelectAreaMin,
                    SelectAreaMax = MBlobCircleParam.SelectAreaMax,
                    SelectRadiusMin = MBlobCircleParam.SelectRadiusMin,
                    SelectRadiusMax = MBlobCircleParam.SelectRadiusMax,
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                var MBlobCircleParam = new BlobCircleParam();
                MBlobCircleParam.Row = 100;
                MBlobCircleParam.Column = 100;
                MBlobCircleParam.Radius = 80;
                MBlobCircleParam.MinGray = 128;
                MBlobCircleParam.MaxGray = 255;
                MBlobCircleParam.OpeningRadius = 40;
                MBlobCircleParam.SelectAreaMin = 10000;
                MBlobCircleParam.SelectAreaMax = 20000;
                MBlobCircleParam.SelectRadiusMin = 50;
                MBlobCircleParam.SelectRadiusMax = 80;
                MBlobCircleParamDisp = new BlobCircleParamDisp
                {
                    Row = MBlobCircleParam.Row,
                    Column = MBlobCircleParam.Column,
                    Radius = MBlobCircleParam.Radius,
                    MinGray = MBlobCircleParam.MinGray,
                    MaxGray = MBlobCircleParam.MaxGray,
                    OpeningRadius = MBlobCircleParam.OpeningRadius,
                    SelectAreaMin = MBlobCircleParam.SelectAreaMin,
                    SelectAreaMax = MBlobCircleParam.SelectAreaMax,
                    SelectRadiusMin = MBlobCircleParam.SelectRadiusMin,
                    SelectRadiusMax = MBlobCircleParam.SelectRadiusMax,
                };
            }
        }
        #endregion
        #region 构造函数
        public FunctionBlobCircleDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "Blob圆形功能";
            IsDrawing = false;
            drawROI = containerProvider.Resolve<DrawROI>();
        }
        #endregion

    }
}
